<template>
  <div class="page">
    <div class="page-content w-1376">
      <div class="header-card">
        <banner-text />
        <collect-card :recently-list="collectCardList" :go="go" @onClick="handleFavorites" />
      </div>
      <div class="header-span-card">
        <div class="flex gap-x-24">
          <div class="classify-text">分类</div>
          <div class="flex flex-wrap gap-x-10 gap-y-16 max-w-1250">
            <template v-for="(item, index) in pageShowClassifyingSystem" :key="index">
              <div
                class="elliptical-1 classify-spans-text"
                :class="[item.status ? 'active' : 'border']"
                :title="item.v"
                @click="handleClassifySpan(item.id)"
              >
                {{ item.v }}
              </div>
            </template>
            <a-button v-if="classifyingSystem.length > DEFAULT_SHOW_LABEL_NUMBER" type="link" @click="handleOpenButton(1)">
              {{ showMoreBtn1 ? '收起' : '更多' }}
            </a-button>
          </div>
        </div>

        <div class="classifying-system-ter">
          <div class="flex gap-x-24 w-100%">
            <div class="flex flex-1">
              <div class="classify-text mr-24">级别</div>
              <div class="flex gap-x-10 gap-y-16 flex-wrap max-w-1250">
                <template v-for="(item, index) in pageShowClassifySpan" :key="index">
                  <div
                    class="elliptical-1 classify-spans-text"
                    :class="[item.status ? 'active' : 'border']"
                    :title="item.v"
                    @click="handleClassifySystem(item.id)"
                  >
                    {{ item.v }}
                  </div>
                </template>
                <a-button v-if="classifySpan.length > DEFAULT_SHOW_LABEL_NUMBER" type="link" @click="handleOpenButton(2)">
                  {{ showMoreBtn2 ? '收起' : '更多' }}
                </a-button>
              </div>
            </div>
          </div>
        </div>

        <div class="classifying-system-ter">
          <div class="flex gap-x-24 w-100%">
            <div class="flex flex-1">
              <div class="classify-text mr-24">查询</div>
              <div class="flex items-end">
                <a-input
                  v-model:value="inputName"
                  v-trim
                  class="w-268 h-36"
                  allow-clear
                  placeholder="请输入课程名称"
                  @press-enter="inputNameChange"
                >
                  <template #prefix><SearchOutlined @click="inputNameChange" /></template>
                </a-input>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="content-cards">
        <content-cards
          v-for="(item, index) in dataList"
          :key="index"
          :data="item"
          @on-click="go(item)"
          @on-collect="classCollectChange"
          @ok-cancel="getDataCollList"
        />
      </div>
      <my-infinite-loading :empty="dataList.length === 0" img-margin-top="120px" :identifier="identifier" @infinite="loadData" />
      <div v-if="dataList.length === 0" class="h-120"></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { debounce } from 'g6-fn'
  import { computed, onMounted, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import BannerText from '@/components/BannerText/index.vue'
  import ContentCards, { ClassSquareCardData } from '@/components/ClassSquareCard/index.vue'
  import CollectCard from '@/components/CollectCard/index.vue'
  import { adminCollectionApi, classSquareApi, tagManageApi } from '@/services/api'

  import { ClassLabelType, UserClassList } from '../types/index'

  const router = useRouter()

  /* 展示更多--------------------------------------------------------------------------------------------------------------------- */
  const DEFAULT_SHOW_LABEL_NUMBER = 18 // 默认显示的标签数量
  const showMoreBtn1 = ref<boolean>(false) //分类
  const showMoreBtn2 = ref<boolean>(false) //级别
  const handleOpenButton = (num: 1 | 2) => {
    if (num === 1) {
      showMoreBtn1.value = !showMoreBtn1.value
      return
    }
    showMoreBtn2.value = !showMoreBtn2.value
  }
  /*---------------------------------------------------------------------------------------------------------------------------------  */

  // 分类
  const classifyingSystem = ref<ClassLabelType[]>([
    {
      createTime: 'string',
      id: '999',
      k: 1,
      pid: 1,
      remark: 'string',
      sort: 1,
      type: 'string',
      updateTime: 'string',
      v: '全部',
      status: true
    }
  ])
  // 页面显示的分类
  const pageShowClassifyingSystem = computed<ClassLabelType[]>(() =>
    classifyingSystem.value.slice(0, showMoreBtn1.value ? classifyingSystem.value.length : DEFAULT_SHOW_LABEL_NUMBER)
  )
  // 级别
  const classifySpan = ref<ClassLabelType[]>([
    {
      createTime: 'string',
      id: '999',
      k: 1,
      pid: 1,
      remark: 'string',
      sort: 1,
      type: 'string',
      updateTime: 'string',
      v: '全部',
      status: true
    }
  ])
  // 页面显示的级别
  const pageShowClassifySpan = computed<ClassLabelType[]>(() =>
    classifySpan.value.slice(0, showMoreBtn2.value ? classifySpan.value.length : DEFAULT_SHOW_LABEL_NUMBER)
  )

  const identifier = ref<number>(1)
  // 查询分类
  const { runAsync: getDataTypeLabel } = useRequest<ResponseData<ClassLabelType[]>>(tagManageApi.list, {
    onSuccess: res => classifySpan.value.push(...res.data.map(item => ({ ...item, status: false })))
  })
  // 查询级别
  const { runAsync: getDataClassLabel } = useRequest<ResponseData<ClassLabelType[]>>(tagManageApi.list, {
    onSuccess: res => classifyingSystem.value.push(...res.data.map(item => ({ ...item, status: false })))
  })

  // 查询当前的课程列表
  const pageForm = ref<UserClassList>({
    categoryId: '',
    columns: 'createTime',
    levelId: '',
    limit: 12,
    name: '',
    offset: 1,
    order: 'asc'
  })

  const dataList = ref<ClassSquareCardData[]>([])

  // 查询列表用于收藏卡片
  const collectCardList = ref<any[]>([])

  // 查询替换收藏卡片数据
  const getDataCollList = async () => {
    let { data } = await adminCollectionApi.getRecentFavorite({ favoriteType: 1, limit: 4 })
    collectCardList.value = data
  }

  const inputName = ref<any>()

  const handleClassifySpan = (id: string) => {
    handleArrDispose(classifyingSystem.value, id)
    // getDataList({ categoryId: id, name: inputName.value })
    pageForm.value.categoryId = id === '999' ? '' : id
    pageForm.value.name = inputName.value
    pageForm.value.offset = 1
    dataList.value = []
    identifier.value = Date.now()
  }

  const handleClassifySystem = (id: string) => {
    handleArrDispose(classifySpan.value, id)
    pageForm.value.levelId = id === '999' ? '' : id
    pageForm.value.name = inputName.value
    pageForm.value.offset = 1
    dataList.value = []
    identifier.value = Date.now()
  }

  // 输入框
  const inputNameChange = debounce(() => {
    pageForm.value.offset = 1
    pageForm.value.name = inputName.value
    dataList.value = []
    identifier.value = Date.now()
  }, 500)

  const handleArrDispose = async (arr: ClassLabelType[], id: string) => {
    // 判断是否是自己
    arr.map(item => {
      if (item.id === id) {
        item.status = true
      } else {
        item.status = false
      }
    })
  }

  const go = (data: any) => {
    window.open(`/class-square/class-particulars/${data.objectId ? data.objectId : data.id}`, '_blank')
  }

  /*----------------------------------------- 点击我的收藏 --------------------------------*/
  const handleFavorites = (item: any) => {
    console.log('item', item)
    router.push({
      path: `/personal-center`,
      query: { tab: 'curriculum', parentTab: 'collect' }
    })
  }

  // 底部滚动
  const loadData = async ($state: any) => {
    try {
      const {
        data: { records }
      } = await classSquareApi.list(pageForm.value)
      if (records.length < pageForm.value.limit) {
        $state.complete()
      } else {
        pageForm.value.offset++
        $state.loaded()
      }
      dataList.value.push(...records)
    } catch (error) {
      $state.error()
    }
  }

  const classCollectChange = async () => {
    getDataCollList()
  }

  const init = async () => {
    await Promise.all([getDataTypeLabel({ type: 'course_level' }), getDataClassLabel({ type: 'course_category' })])
    await getDataCollList()
  }

  onMounted(() => {
    init()
  })
</script>
<style lang="less" scoped>
  .page {
    display: flex;
    justify-content: center;
    // padding: 24px 20px 20px;
    padding-top: 24px;
    padding-bottom: 1px;
    width: 100%;

    .header-span-card {
      padding: 24px;
      margin: 12px 0 24px;
      width: 100%;
      background-color: @background1;
      border: 1px solid @border1;
      border-radius: 10px;
    }

    .classify-spans {
      display: flex;
    }

    .classifying-system-spans {
      display: flex;
      gap: 12px;
      align-items: center;
      flex-wrap: wrap;
    }

    .classifying-system-input {
      width: 268px;
      height: 36px;
    }

    .classifying-system-ter {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 16px;
    }

    .classify-text {
      margin-top: 0;
      height: 100%;
      font-size: 14px;
      color: rgba(21, 23, 27, 0.95);
      font-weight: 700;
      line-height: 30px;
    }
  }

  .classify-spans-text {
    padding: 4px 12px;
    max-width: 190px;
    height: 30px;
    text-align: center;
    border-radius: 6px;
    line-height: 30px;
    cursor: pointer;
    .font14();

    &:hover {
      background: rgba(0, 0, 0, 0.05);
    }

    &.border {
      color: @text02;
    }

    &.active {
      color: #1868e9;
      background-color: #1868e91a;
    }
  }

  .content-cards {
    display: flex;
    flex-wrap: wrap;
    max-width: 1376px;
    // gap: 10px;
    gap: 20px;
    row-gap: 24px;
    grid-template-columns: repeat(auto-fill, minmax(329px, 1fr));
  }

  .header-card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    margin-bottom: 24px;
    width: 100%;
    background: url('@/assets/img/224.png');
    border: 1px solid var(--mask-2, rgba(0, 0, 0, 0.1));
    border-radius: 12px;
    box-shadow: 0 1px 5px 0 rgba(66, 132, 237, 0.2);
  }

  .infinite-box {
    display: flex;
    justify-content: center;
    width: 1376px;
  }
</style>
